// 98. 验证二叉搜索树
// https://leetcode.cn/problems/validate-binary-search-tree/

/**
输入：root = [2,1,3]
输出：true
示例 2：


输入：root = [5,1,4,null,null,3,6]
输出：false
解释：根节点的值是 5 ，但是右子节点的值是 4 。
 */

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function (root) {
    let arr = centerScan(root);

    let result = checkValidArr(arr);
    console.log(`${JSON.stringify(arr)} ${result}`);
    return result;
};

function checkValidArr(arr) {
    for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i + 1] <= arr[i]) return false;
    }

    return true;
}

function centerScan(root) {
    if (!root || root.val === null) return [];
    if (root.left === null && root.right === null) return root.val;

    let leftArr = centerScan(root.left);
    let rightArr = centerScan(root.right);

    return [].concat(leftArr).concat(root.val).concat(rightArr);
}

function TreeNode(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
}

function genTreeNode(arr) {
    let arrNode = arr.map((i) => (i != null ? new TreeNode(i) : null));
    for (let i = 0; i < arrNode.length; i++) {
        const leftIndex = 2 * i + 1;
        const rightIndex = 2 * i + 2;

        if (leftIndex >= arrNode.length) break;

        if (arrNode[i] !== null && arrNode[i].val !== null) {
            arrNode[i].left = arrNode[leftIndex];
            arrNode[i].right = arrNode[rightIndex];
        }
    }

    return arrNode[0];
}

isValidBST(genTreeNode([2, 1, 3]));
isValidBST(genTreeNode([5, 1, 4, null, null, 3, 6]));
isValidBST(genTreeNode([2, 2, 2]));
isValidBST(genTreeNode([1, 1])); //
isValidBST(genTreeNode([0, null, -1]));
